package sync

import (
	"SyncArgoCD/model"
	"SyncArgoCD/util"
	"net/http"
)

func ArgoSync(token string) string {
	//sync := "{\"revision\":\"HEAD\",\"prune\":true,\"dryRun\":false,\"strategy\":{\"hook\":{\"force\":true}},\"resources\":null,\"syncOptions\":{\"items\":[\"CreateNamespace=true\",\"PrunePropagationPolicy=orphan\",\"PruneLast=true\",\"Replace=true\"]}}"
	var forceData = new(ForceSync)
	forceData.Revision = "HEAD"
	forceData.Prune = true
	forceData.DryRun = false
	forceData.Strategy.Hook.Force = true
	forceData.SyncOptions.Items = [4]string{"CreateNamespace=true", "PrunePropagationPolicy=orphan", "PruneLast=true", "Replace=true"}
	var header = map[string]string{}
	header["Cookie"] = "Cookie: rem-username=admin; argocd.token=" + token
	result, err := util.PostHeader(model.SyncUrl.Url, header, forceData, "application/json")
	if err != nil {
		return err.Error()
	}
	return result
}

type ArgoSyncHandler struct{}

func (ArgoSyncHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	token := Login()
	result := ArgoSync(token)
	_, err := w.Write([]byte(result))
	if err != nil {
		return
	}
}

type ArgoLoginHandler struct{}

func (ArgoLoginHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	token := Login()
	_, err := w.Write([]byte(token))
	if err != nil {
		return
	}
}

type ArgoSyncWithoutLoginHandler struct{}

func (ArgoSyncWithoutLoginHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	result := ArgoSync("")
	_, err := w.Write([]byte(result))
	if err != nil {
		return
	}
}

type HelloHandler struct{}

func (HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	_, err := w.Write([]byte("hello world"))
	if err != nil {
		return
	}
}

func ArgoSyncApplication() {
	http.Handle("/argocd/syncApplication", ArgoSyncHandler{})
}
func ArgoLogin() {
	http.Handle("/argocd/login", ArgoLoginHandler{})
}
func ArgoSyncWithoutLogin() {
	http.Handle("/argocd/syncWithoutLogin", ArgoSyncWithoutLoginHandler{})
}
func Hello() {
	http.Handle("/argocd/hello", HelloHandler{})
}

type ForceSync struct {
	Revision string `json:"revision"`
	Prune    bool   `json:"prune"`
	DryRun   bool   `json:"dryRun"`
	Strategy struct {
		Hook struct {
			Force bool `json:"force"`
		} `json:"hook"`
	} `json:"strategy"`
	Resources   interface{} `json:"resources"`
	SyncOptions struct {
		Items [4]string `json:"items"`
	} `json:"syncOptions"`
}
